# -*- encoding: utf-8 -*-
import time

from packages import AppPackages


def wait_element(element, timeout=30):
    while timeout > 0:
        if element.exists:
            return True
        timeout -= .5
        time.sleep(.5)
    return False


class Weibo:
    def __init__(self, drive):
        self._drive = drive
        self._packages_name = AppPackages.weibo.packages_name

    def open_app(self):
        self._drive.app_start(self._packages_name)
        return True

    def stop_app(self):
        self._drive.app_stop(self._packages_name)
        return True

    def login(self):
        self.open_app()
        my_element = self._drive.xpath(
            '//*[@resource-id="com.sina.weibo:id/main_radio"]/android.widget.FrameLayout[5]'
        )
        if wait_element(my_element) is False:
            return
        my_element.click()
        scan_button = self._drive.xpath(
            '//*[@resource-id="android:id/tabcontent"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.ImageView[2]'
        )
        if wait_element(scan_button) is False:
            return
        scan_button.click()
        photo = self._drive(resourceId="com.sina.weibo:id/scan_my_photo_icon")
        if wait_element(photo) is False:
            return
        photo.click()
